// 引入API模块
const api = require('../../utils/api/index');

Page({
  data: {
    recipeId: null,
    loading: true,
    recipe: {},
    carbsPercent: 0,
    proteinPercent: 0,
    fatPercent: 0
  },

  onLoad: function(options) {
    // 检查是否有recipeId参数
    if (options && options.id) {
      this.setData({
        recipeId: options.id
      });
      this.loadRecipeDetail(options.id);
    } else {
      wx.showToast({
        title: '缺少食谱ID',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载食谱详情
  loadRecipeDetail: async function(id) {
    try {
      this.setData({ loading: true });
      
      // 调用API获取食谱详情
      const result = await api.diet.getRecipeById(id);
      
      if (result && result.success && result.data) {
        const recipe = result.data;
        
        // 计算营养素百分比
        const totalMacros = recipe.carbs + recipe.protein + recipe.fat;
        const carbsPercent = Math.round((recipe.carbs / totalMacros) * 100) || 0;
        const proteinPercent = Math.round((recipe.protein / totalMacros) * 100) || 0;
        const fatPercent = Math.round((recipe.fat / totalMacros) * 100) || 0;
        
        this.setData({
          recipe,
          carbsPercent,
          proteinPercent,
          fatPercent,
          loading: false
        });
      } else {
        throw new Error('获取食谱详情失败');
      }
    } catch (error) {
      console.error('加载食谱详情失败:', error);
      wx.showToast({
        title: '获取食谱详情失败',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 收藏食谱（开发中功能）
  toggleFavorite: function() {
    wx.showToast({
      title: '收藏功能开发中',
      icon: 'none'
    });
  },

  // 分享食谱
  share: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    });
  },

  // 分享配置
  onShareAppMessage: function() {
    return {
      title: this.data.recipe.name || '健康食谱推荐',
      path: `/pages/recipeDetail/recipeDetail?id=${this.data.recipeId}`,
      imageUrl: this.data.recipe.imageUrl
    };
  }
}); 